package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceServiceVo;
import com.zzyl.nursing.vo.ProductVo;
import okhttp3.Request;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;


    @Autowired
    private IoTDAClient iotDAClient;


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }
    /**
     * 同步产品列表
     *
     * @return
     */
    @Override
    public void syncProductList() {

        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(10);

        ListProductsResponse response = iotDAClient.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String str = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);

        if (StringUtils.isEmpty(str)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(str, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional
    public void register(DeviceDto dto) {
        //判断设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //设备标识是否重复
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备标识重复");
        }
        //同一位置是否绑定了相同产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );
        if (count>0) {
             throw new BaseException("同一位置已绑定相同产品");
        }
        //注册设备到iot
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        body.setAuthInfo(authInfo);
        authInfo.withSecret(secret);

        request.setBody(body);

        AddDeviceResponse response = iotDAClient.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("设备注册失败");
        }

        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setBindingLocation(dto.getBindingLocation()+ "");
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        //本地保存设备
        this.save(device);

    }
    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查询本地数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //如果为空，返回null
        if (device == null) {
           return null;
        }
        //查询iot云端的数据详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = iotDAClient.showDevice(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("查询设备详情失败");
        }
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);
        vo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if (activeTime != null){
            LocalDateTime activetime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            vo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activetime));
        }
        return vo;
    }
    /**
     * 查询设备上报的数据
     *
     * @param iotId 设备标识
     * @return
     */

    @Override
    public List<DeviceServiceVo> queryServiceProperties(String iotId) {
        //查询设备上报的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new RuntimeException("查询设备影子失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollectionUtil.isEmpty( shadow)){
            List<DeviceServiceVo> emptyList = Collections.emptyList();
           return emptyList;
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        String eventTime = reported.getEventTime();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        List<DeviceServiceVo>  list = new ArrayList<>();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime time = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

        jsonObject.forEach((key, value) -> {
            DeviceServiceVo vo = new DeviceServiceVo();
            vo.setFunctionId(key);
            vo.setValue(value != null ? String.valueOf(value) : null);
            vo.setEvenTime(time);
            list.add(vo);
        });
        return  list;
    }

    /**
     * 修改设备信息
     * @param dto
     */

    @Override
    @Transactional
    public void edit(DeviceDto dto) {
        //修改IOT平台上的设备名称

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse response = iotDAClient.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("修改设备名称失败");
        }
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setBindingLocation(dto.getBindingLocation()+ "");
        //注意：修改时，不能在同一个位置绑定同一个产品
        //同一位置是否绑定了相同产品
        long count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );
        if (count > 0){
            throw new BaseException("同一位置已绑定相同产品");
        }
        //修改本地的存储信息
        this.updateById(device);
    }


    /**
     * 删除设备
     * @param iotId
     */
    @Override
    @Transactional
    public void deleteDev(String iotId) {

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = iotDAClient.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("删除设备失败");
        }

        Device dev = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        this.removeById(dev);
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = iotDAClient.showProduct(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("查询产品失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtil.isEmpty(serviceCapabilities)) {
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }
}
